<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <el-form
        :model="spuinfo"
        :rules="rules"
        ref="rulesInput"
        label-width="80px"
        :inline="false"
        size="normal"
      >
        <el-form-item label="SPU名称" prop="spuName">
          <el-input v-model="spuinfo.spuName"></el-input>
        </el-form-item>
        <el-form-item label="品牌" prop="tmId">
          <el-select v-model="spuinfo.tmId" clearable filterable>
            <el-option
              :value="item.id"
              :label="item.tmName"
              v-for="item in tradeMarkList"
              :key="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="SPU描述" size="normal" prop="description">
          <el-input type="textarea" v-model="spuinfo.description"></el-input>
        </el-form-item>
        <el-form-item label="SPU图片" size="normal">
          <el-upload
            :action="`${baseURl}/admin/product/fileUpload`"
            list-type="picture-card"
            :file-list="fileList"
            :on-success="handleAvatarSuccess"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="销售属性" size="normal">
          <el-select v-model="salechangeValue" clearable filterable>
            <el-option
              :value="`${item.id}:${item.name}`"
              :label="item.name"
              v-for="item in lastSaleList"
              :key="item.id"
            >
            </el-option>
          </el-select>
          <el-button
            type="primary"
            size="medium"
            :style="{ marginLeft: '20px' }"
            @click="addsaleItem"
          >
            添加销售属性</el-button
          >
          <el-table :data="spuinfo.spuSaleAttrList" border stripe>
            <el-table-column label="序号" type="index" width="80">
            </el-table-column>
            <el-table-column
              label="属性值"
              width="180"
              prop="saleAttrName"
            ></el-table-column>
            <el-table-column label="属性值名称列表">
              <template v-slot="{ row }">
                <el-tag
                  type="success"
                  size="normal"
                  effect="dark"
                  closable
                  @close="delTag(row, index)"
                  v-for="(item, index) in row.spuSaleAttrValueList"
                  :key="index"
                  >{{ item.saleAttrValueName }}</el-tag
                >
                <el-form-item size="normal">
                  <el-input
                    ref="saleAttrValueInput"
                    placeholder=""
                    size="normal"
                    v-if="row.isWriteMode"
                    clearable
                    v-model="saleAttrValue"
                    @blur="changeLookMode(row)"
                  ></el-input>
                  <el-button
                    type="info"
                    size="mini"
                    icon="el-icon-plus"
                    @click="changeWriteMode(row)"
                    v-else
                  ></el-button>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template v-slot="{ $index }">
                <el-button
                  type="danger"
                  size="medium"
                  icon="el-icon-delete"
                  @click="delsaleAttrItem($index)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item size="normal">
          <el-button type="primary" size="medium" @click="saveSpuinfo"
            >保存</el-button
          >
          <el-button
            type="primary"
            size="medium"
            @click="$emit('changeIndex', 0)"
            >取消</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { reqAttrlist } from "@/api/attrs";
import { reqAlltrademark } from "@/api/trademake";
import {
  addSpuInfo,
  reqImageList,
  reqAttrsList,
  updateSpuInfo,
} from "@/api/spu";
import { mapState } from "vuex";
export default {
  name: "Spuinfo",
  props: ["spuinfo"],
  data() {
    return {
      imageUrl: "",
      attrList: [],
      tradeMarkList: [],
      salechangeValue: "",
      // 准备添加的属性值数据
      saleAttrValue: "",
      // 图片墙
      fileList: [],
      ImageList: [],
      //创建环境变量前缀
      baseURl: process.env.VUE_APP_BASE_API,
      //添加表单验证
      rules: {
        spuName: [
          { required: true, message: "请输入SPU名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        description: [
          { required: true, message: "请输入描述", trigger: "blur" },
        ],
        tmId: [{ required: true, message: "请选择品牌", trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.getinitDate();
    // 检测是否在spuinfo中含有id,如果有就需要将其的图片列表覆盖到fileList中
    if (typeof this.spuinfo.id !== "undefined") {
      console.log("date");
      this.reDate(this.spuinfo.id);
    }
  },
  computed: {
    ...mapState("category", ["category3id"]),
    // 希望销售列表会随着数据添加而减少,使用计算属性对比
    lastSaleList() {
      return this.attrList.filter((el) => {
        return this.spuinfo.spuSaleAttrList.every(
          (itme) => itme.baseSaleAttrId != el.id
        );
      });
    },
  },
  methods: {
    //初始化数据
    async reDate(id) {
      let reImgList = await reqImageList(id);
      this.spuinfo.spuSaleAttrList = await reqAttrsList(id);
      reImgList.forEach((item) => {
        this.fileList.push({
          name: item.imgName,
          url: item.imgUrl,
        });
      });
    },
    handleAvatarSuccess(res, file) {
      this.fileList.push({
        name: file.name,
        url: file.response.data,
      });
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //初始化获取reqAttrlist和tradeMark数据
    async getinitDate() {
      let attrList = await reqAttrlist();
      let tradeMarkList = await reqAlltrademark();
      this.attrList = attrList;
      this.tradeMarkList = tradeMarkList;
    },
    // 新增销售属性
    addsaleItem() {
      // 非空
      if (!this.salechangeValue) return;
      const [baseSaleAttrId, saleAttrName] = this.salechangeValue.split(":");
      this.spuinfo.spuSaleAttrList.push({
        baseSaleAttrId,
        saleAttrName,
        isWriteMode: false,
        spuSaleAttrValueList: [],
      });
      // 添加后删除当前input中值
      this.salechangeValue = "";
    },
    // 切换到书写模式
    changeWriteMode(row) {
      // 清除上一次的添加数据
      this.saleAttrValue = "";
      row.isWriteMode = true;
      this.$nextTick(() => {
        this.$refs.saleAttrValueInput.focus();
      });
    },
    changeLookMode(row) {
      // 去重
      const flag = row.spuSaleAttrValueList.every(
        (item) => item.saleAttrValueName !== this.saleAttrValue
      );
      // 非空判断
      if (!this.saleAttrValue || !flag) return (row.isWriteMode = false);

      row.spuSaleAttrValueList.push({
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrName: row.saleAttrName,
        saleAttrValueName: this.saleAttrValue,
      });
      row.isWriteMode = false;
    },
    saveSpuinfo() {
      //进行整体校验
      this.$refs.rulesInput.validate(async (e) => {
        if (e) {
          // 发送新增请求;
          // 重新获取一次3id;
          this.spuinfo.category3Id = this.category3id;
          // 提取图片信息
          const arr = [];
          this.fileList.forEach((item) => {
            arr.push({
              imgName: item.name,
              imgUrl: item.url,
            });
          });
          // 不能直接push,直接push会导致变多
          this.spuinfo.spuImageList = arr;

          //根据id判断请求类型
          if (this.spuinfo.id) {
            await updateSpuInfo(this.spuinfo);
            this.$message({
              type: "success",
              message: "修改数据成功",
            });
          } else {
            await addSpuInfo(this.spuinfo);
            this.$message({
              type: "success",
              message: "新增数据成功",
            });
          }
          this.$emit("changeIndex", 0);
        }
      });
    },
    // 删除单个tag
    delTag(row, index) {
      row.spuSaleAttrValueList.splice(index, 1);
    },
    // 删除单个销售属性
    delsaleAttrItem(index) {
      this.spuinfo.spuSaleAttrList.splice(index, 1);
    },
  },
};
</script>

<style >
.avatar-uploader .el-upload {
  border: 3px solid #8c939d;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>